#include<iostream>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<cstdio>
#include<cstring>

void ChildWrite(int wfd)
{
    char buffer[1024] = {0};
    int cnt = 0;
    while(true)
    {
        //为什么sizeof不用-1？
        //因为snprintf会自动在结尾添加\0，而系统调用write不需要\0 
        snprintf(buffer, sizeof(buffer), "I am child,pid = %d, cnt = %d\n", getpid(), cnt++);
        write(wfd, buffer, strlen(buffer));
        sleep(1);
    }
};

void ParentRead(int rfd)
{
    char buffer[1024] = {0};
    while(true)
    {
        buffer[0] = 0;
        ssize_t n = read(rfd, buffer, sizeof(buffer)-1);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << "Child say: " << buffer << std::endl;
        }
    }
};

int main()
{
    //1.创建管道
    int fds[2] = {0};
    //fds[0] -> read
    //fds[1] -> write
    int n = pipe(fds);
    if(n < 0)
    {
        std::cerr << "pipe error" << std::endl;
        return 1;
    }
    std::cout << "fds[0]: " << fds[0] << std::endl;
    std::cout << "fds[1]: " << fds[1] << std::endl;

    //2.创建子进程
    pid_t id = fork();
    if (id == 0)
    {
        //child
        //code
        //3.关闭读写端，形成单向通信
        //f -> read, c -> write
        close(fds[0]);
        ChildWrite(fds[1]);
        close(fds[1]);
        exit(0);
    }
    //3.关闭读写端，形成单向通信
    //f -> read, c -> write
    close(fds[1]);
    ParentRead(fds[0]);
    waitpid(id, nullptr, 0);
    close(fds[0]);
    return 0;
}